//
//  AllBrandsViewController.swift
//  koolcar
//
//  Created by kuaimaxiansheng on 2023/10/10.
//

import UIKit
import TTIndexBar


protocol BrandSearchViewDelegate{
    func selectBrandData(dataArray: NSMutableArray)
}


class AllBrandsViewController: BaseViewController {
    
    var delegate: BrandSearchViewDelegate!
    var tableView: BaseTableView!
    var indexBar: TTIndexBar!
//    let letters = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z","#"]
    var filtratBtn: UIButton!
    var brandNameArray: [BrandSeriesListModel] = []//品牌
    var groupedArray: [MapKey] = []
    var selectBrandArray = NSMutableArray()//选中品牌
    var seaData: FilterDataModel? //海外车
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navBar.title = MMLocalizedString("all_brands", comment: "全部品牌")
        self.view.backgroundColor = Theme.F5Color
        self.initTableView()
        self.buttomTabbar()
        if self.seaData != nil {
            self.seaDealData()
        }else{
            self.requestAllBrandSerisesInfo()
        }
    }
    func initTableView(){
        
        self.tableView = BaseTableView(frame: CGRect(x: 0, y: NavBarHight, width: kScreenWidth, height: kScreenHeight), style: .plain)
        self.tableView.register(AllBrandsTableViewCell.self, forCellReuseIdentifier: "AllBrandsTableViewCell")
        self.tableView.rowHeight = UITableViewAutomaticDimension
        self.tableView.estimatedRowHeight = 44
        self.tableView.delegate = self
        self.tableView.dataSource = self
        self.tableView.backgroundColor = Theme.F5Color
        self.view.addSubview(self.tableView)
        
        self.indexBar = TTIndexBar(frame: CGRect.zero)
        self.indexBar.delegate = self
        self.indexBar.textColor = UIColor(hex: 0x939AA8)
        self.indexBar.selectedTextColor = UIColor(hex: 0xDBC283)
        self.indexBar.detailViewDrawColor = UIColor(hex: 0xDBC283)
        self.indexBar.detailViewTextColor = .white
        self.indexBar.selectedBackgroundColor = .clear
        self.indexBar.sectionHeight = 20
        self.view.addSubview(self.indexBar)
       
        
        self.tableView.snp.makeConstraints { make in
            make.top.equalTo(NavBarHight)
            make.left.equalTo(0)
            make.right.equalTo(0)
            make.bottom.equalTo(-TabbarHeight)
        }
        
        self.indexBar.snp.makeConstraints { make in
            make.right.equalTo(0)
            make.width.equalTo(23)
            make.centerY.equalTo(self.view.snp.centerY)
            make.height.equalTo(kScreenHeight - TabbarHeight - NavBarHight)
        }
  
    }
    
    override func backAction() {
        if self.navigationController?.viewControllers.count ?? 0 > 1 {
            self.navigationController?.popViewController(animated: true)
        }else{
            self.dismiss(animated: true)
        }
    }
    
    
    func buttomTabbar(){
        let bgView = UIView(frame: CGRect(x: 0, y: kScreenHeight - TabbarHeight - 10, width: kScreenWidth, height: TabbarHeight))
        bgView.backgroundColor = Theme.F5Color
        self.view.addSubview(bgView)
        
        self.filtratBtn = UIButton(frame: CGRect(x: 14, y: 10, width: kScreenWidth - 28, height: 46))
        self.filtratBtn.backgroundColor = Theme.mainColor
        self.filtratBtn.titleLabel?.font = UIFont.init(name: Theme.PingFangSCMedium, size: 16)
        self.filtratBtn.setTitle(MMLocalizedString("confirm", comment: "确定"), for: .normal)
        self.filtratBtn.setTitleColor(.white, for: .normal)
        self.filtratBtn.layer.cornerRadius = 8
        self.filtratBtn.clipsToBounds = true
        self.filtratBtn.addTarget(self, action: #selector(filtratBtnAntion), for: .touchUpInside)
        bgView.addSubview(self.filtratBtn)
        
    }
    
    ///海外车
    private func seaDealData(){
        let tempList = self.seaData?.katashikiList ?? []
        tempList.forEach { item in
            if item.first == nil || item.first == "" {
                item.first = "#"
            }
        }
        
        let resultArr = tempList.map { katashikiListData in
            let item = BrandSeriesListModel()
            item.brandName = katashikiListData.brandName ?? ""
            item.id = Int(katashikiListData.brandId ?? "0")
            item.isSelect = false
            item.first = katashikiListData.first ?? "#"
            let list = katashikiListData.katashiki ?? []
            var tempList:[SeriesListModel] = []
            for (pIndex, pObj) in list.enumerated() {
                let pItem = SeriesListModel()
                pItem.isSelect = false
                pItem.name = pObj
                pItem.id = pIndex
                tempList.append(pItem)
            }
            item.seriesList = tempList
            return item
        }
        
        self.brandNameArray = resultArr
        //归类
        let groupedData = Dictionary(grouping: self.brandNameArray, by: { $0.first })
        if let tempData = groupedData as? NSDictionary {
            let keyList = tempData.allKeys
            var tempKeyList: [String] = []
            keyList.forEach { item in
                if let str = item as? String {
                    tempKeyList.append(str)
                }else{
                    tempKeyList.append("#")
                }
            }
            tempKeyList.sort()//排序
            if let index = tempKeyList.firstIndex(of: "#") {//把#放在最后面
                tempKeyList.append(tempKeyList.remove(at: index))
            }
            tempKeyList.forEach { item in
                let brand = tempData[item] as? [BrandSeriesListModel]
                let mapKeyObj = MapKey.init(aKey: item, data: brand)
                self.groupedArray.append(mapKeyObj)
            }
            
            self.indexBar.setIndexes(tempKeyList)
            let hh = groupedData.count * 22
            self.indexBar.snp.updateConstraints { make in
                make.height.equalTo(hh)
            }
            self.updateViewConstraints()
        }
        self.tableView.reloadData()
    }
    
    //所有品牌及车系
    func requestAllBrandSerisesInfo(){
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.allBrandSerisesInfo, objectType: BrandNameModel.self) { data in
            let resultObj = data as! BrandNameModel
            if resultObj.code == "1" {
                let tempList = resultObj.data ?? []
                tempList.forEach { item in
                    if item.first == nil || item.first == "" {
                        item.first = "#"
                    }
                }
                self.brandNameArray = tempList
                //归类
                let groupedData = Dictionary(grouping: self.brandNameArray, by: { $0.first })
                if let tempData = groupedData as? NSDictionary {
                    let keyList = tempData.allKeys
                    var tempKeyList: [String] = []
                    keyList.forEach { item in
                        if let str = item as? String {
                            tempKeyList.append(str)
                        }else{
                            tempKeyList.append("#")
                        }
                    }
                    tempKeyList.sort()//排序
                    if let index = tempKeyList.firstIndex(of: "#") {//把#放在最后面
                        tempKeyList.append(tempKeyList.remove(at: index))
                    }
                    tempKeyList.forEach { item in
                        let brand = tempData[item] as? [BrandSeriesListModel]
                        let mapKeyObj = MapKey.init(aKey: item, data: brand)
                        self.groupedArray.append(mapKeyObj)
                    }
                    
                    self.indexBar.setIndexes(tempKeyList)
                    let hh = groupedData.count * 22
                    self.indexBar.snp.updateConstraints { make in
                        make.height.equalTo(hh)
                    }
                    self.updateViewConstraints()
                }
            }
            self.tableView.reloadData()
        } error: { err in
            self.view.makeToast(message: err?.domain ?? "")
        }
    }
   
    //MARK: - Antion
    @objc func filtratBtnAntion(){
        self.selectBrandArray.removeAllObjects()
        for index in 0 ..< self.groupedArray.count{
            let model = self.groupedArray[index]
            for i in 0 ..< (model.data?.count ?? 0) {
                let contetModel = model.data?[i]
                if contetModel?.isSelect == true{
                    self.selectBrandArray.add(contetModel as Any)
                }
            }
        }
        self.delegate?.selectBrandData(dataArray: self.selectBrandArray)
        self.backAction()
    }

}

extension AllBrandsViewController: UITableViewDelegate,UITableViewDataSource{
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return self.groupedArray.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let model = self.groupedArray[section]
        return model.data?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 43
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "AllBrandsTableViewCell", for: indexPath) as! AllBrandsTableViewCell
        if self.groupedArray.count > indexPath.count{
            let keyModel = self.groupedArray[indexPath.section]
            let model =  keyModel.data?[indexPath.row]
            cell.setContentModel(model: model!)
        }
       
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 40
    }
    
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let headerView = UIView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: 40))
        headerView.backgroundColor = Theme.F5Color
        let titleLab = UILabel(frame: CGRect(x: 20, y: 0, width: kScreenWidth - 40, height: 40))
        titleLab.textColor = Theme.titleLabColor
        titleLab.textAlignment = .left
        titleLab.font = UIFont.init(name: Theme.PingFangSCMedium, size: 14)
        headerView.addSubview(titleLab)
        
       //setModel
        let model = self.groupedArray[section]
        titleLab.text = model.aKey
        return headerView
    }
    
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 5
    }
    
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let footerView = UIView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: 1))
        footerView.backgroundColor = Theme.F5Color
        
        let line = UIView(frame: CGRect(x: 14, y: 4, width: kScreenWidth - 56, height: 1))
        line.backgroundColor = UIColor(hex: 0x939AA8,alpha: 0.12)
        footerView.addSubview(line)
        
        return footerView
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let model = self.groupedArray[indexPath.section]
        if (model.data ?? []).count > indexPath.row {
            let contetModel = model.data?[indexPath.row]
            contetModel?.isSelect = !contetModel!.isSelect
            for index in 0 ..< self.groupedArray.count{//单选
                let groupeModel = self.groupedArray[index]
                groupeModel.data?.forEach({ item in
                    if contetModel?.id == item.id{
                        item.isSelect = contetModel?.isSelect ?? false
                    }else{
                        item.isSelect = false
                    }
                })
            }
            self.tableView.reloadData()
        }
    }
    
    
    
}

extension AllBrandsViewController: TTIndexBarDelegate{
    func indexDidChanged(_ indexBar: TTIndexBar!, index: Int, title: String!) {
        
        for groupIndex in 0 ..< self.groupedArray.count {
            let model = self.groupedArray[groupIndex]
            if title.uppercased() == model.aKey.uppercased(){
                let indexPath = IndexPath(row: 0, section: groupIndex)   //滑动到指定section
                self.tableView.scrollToRow(at: indexPath, at: .top, animated: true)
            }
        }

        if(title == "#"){
            let num = self.groupedArray.count - 1
            let indexPath = IndexPath(row: 0, section: num)
            self.tableView.scrollToRow(at: indexPath, at: .top, animated: true)
        }
    }
}



